import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.UUID;

public class EncodeDecode {
    public static void main(String[] args) {
        System.out.println("常见加解密");
        uuid();
        System.out.println("========================");
        randomInt();
        System.out.println("========================");
        currentTime();

        System.out.println("========================");
        base64();

        String name = "lanlang";
        // 换成byte

        System.out.println("md5加密:"+ encodeMD5("123456"));
    }

    public static final String encodeMD5(String str) {
        final byte m = 15;
        char[] cArr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] bytes = str.getBytes();
            MessageDigest instance = MessageDigest.getInstance("MD5");
            instance.update(bytes);
            byte[] digest = instance.digest();
            int length = digest.length;
            char[] cArr2 = new char[(length * 2)];
            int i = 0;
            for (byte b : digest) {
                int i2 = i + 1;
                cArr2[i] = cArr[(b >>> 4) & 15];
                i = i2 + 1;
                cArr2[i2] = cArr[b & m];
            }
            return new String(cArr2).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    // Base64转换
    public static void base64()
    {
        String name = "xing";
        Base64.Encoder encoder = Base64.getEncoder();
        String base64Str = encoder.encodeToString(name.getBytes());
        System.out.println("base64Str:"+base64Str);

        // 解码
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] res = decoder.decode(base64Str);
        String srcStr = new String(res);
        System.out.println("res:"+srcStr);
    }

    public static void currentTime()
    {
        // 获取当前时间戳
        long t = System.currentTimeMillis();  // 返回的是毫秒级别的时间戳
        System.out.println(t);
        System.out.printf("13位时间戳:%d\n", t);
        String tt1 = String.valueOf(t);
        System.out.printf("13位时间戳%s\n", tt1);

        // 转化为10位的时间戳
        String tt2 = String.valueOf(t/1000);
        System.out.printf("10位的时间戳:%s", tt2);
    }

//    生成UUID
    public static void uuid() {
        String uuid = UUID.randomUUID().toString();
        System.out.println("生成的UUID:"+uuid);
        System.out.println("长度:"+uuid.length());
    }

    public static void randomInt() {
        BigInteger bn = new BigInteger(80, new SecureRandom());
//        String s = bn.toString();
        String s = bn.toString(16);  // 转成16进制:1c4b0b38fa40e4eed052
        System.out.println("随机数字:"+s);
        System.out.println("长度:"+s.length());
    }
}




